package com.cmhi.softmbh.provider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import androidx.annotation.NonNull;

import java.util.HashMap;
import java.util.Objects;

/**
 * 对HuaWei表进行操作的ContentProvider
 * @author jacp
 */
public class BaiMengProvider extends ContentProvider {
    private static final int LEADERS = 1;
    //    private static final int LEADER_ID = 2;
    private static final UriMatcher sUriMatcher;
    private DatabaseHelper mOpenHelper;

    @Override
    public boolean onCreate() {
        mOpenHelper = new DatabaseHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        //AppUtils.debugLog(Arrays.toString(selectionArgs));
        Cursor mCur = null;
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        if (db != null && db.isOpen()) {
            if (Provider.ZhongXingColumns.TABLE_NAME.equals(uri.getLastPathSegment())) {
                mCur = db.query(Provider.ZhongXingColumns.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
            } else {
                mCur = db.query(Provider.ZhongXingColumns.TABLE_NAME, null, Provider.ZhongXingColumns.NAME +
                        " = '" + uri.getLastPathSegment() + "'", null, null, null, sortOrder);
            }
        }
        return mCur;

//        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
//        qb.setTables(Provider.ZhongXingColumns.TABLE_NAME);
//        switch (sUriMatcher.match(uri)) {
//            case PROGRAMMERS:
//                qb.setProjectionMap(sprogrammersProjectionMap);
//                break;
////            case PROGRAMMERS_ID:
////                qb.setProjectionMap(sprogrammersProjectionMap);
////                qb.appendWhere(Provider.ZhongXingColumns._ID + "=" + uri.getPathSegments().get(1));
////                break;
//            default:
//                throw new IllegalArgumentException("Unknown URI " + uri);
//        }
//        // If no sort order is specified use the default
//        String orderBy;
//        if (TextUtils.isEmpty(sortOrder)) {
//            orderBy = Provider.ZhongXingColumns.DEFAULT_SORT_ORDER;
//        } else {
//            orderBy = sortOrder;
//        }
//        // Get the database and run the query
//        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
//        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
//        // Tell the cursor what uri to watch, so it knows when its source data changes
//        c.setNotificationUri(getContext().getContentResolver(), uri);
//        return c;
    }

    @Override
    public String getType(@NonNull Uri uri) {
        switch (sUriMatcher.match(uri)) {
            case LEADERS:
                return Provider.CONTENT_TYPE;
//            case LEADER_ID:
//                return Provider.CONTENT_ITEM_TYPE;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }

    @Override
    public Uri insert(@NonNull Uri uri, ContentValues initialValues) {
        // Validate the requested uri
        if (sUriMatcher.match(uri) != LEADERS) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }

        // Make sure that the fields are all set
        if (!values.containsKey(Provider.HuaWeiColumns.NAME)) {
            values.put(Provider.HuaWeiColumns.NAME, "");
        }

        if (!values.containsKey(Provider.HuaWeiColumns.VALUE)) {
            values.put(Provider.HuaWeiColumns.VALUE, "");
        }

        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        long rowId = db.insert(Provider.HuaWeiColumns.TABLE_NAME, Provider.HuaWeiColumns.NAME, values);
        if (rowId > 0) {
            Uri noteUri = ContentUris.withAppendedId(Provider.HuaWeiColumns.CONTENT_URI, rowId);
            Objects.requireNonNull(getContext()).getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
    }

    @Override
    public int delete(@NonNull Uri uri, String where, String[] whereArgs) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
            case LEADERS:
                count = db.delete(Provider.HuaWeiColumns.TABLE_NAME, where, whereArgs);
                break;

//            case LEADER_ID:
//                String noteId = uri.getPathSegments().get(1);
//                count = db.delete(Provider.HuaWeiColumns.TABLE_NAME, Provider.HuaWeiColumns._ID + "=" + noteId
//                        + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
//                break;

            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        Objects.requireNonNull(getContext()).getContentResolver().notifyChange(uri, null);
        return count;
    }

    @Override
    public int update(@NonNull Uri uri, ContentValues values, String where, String[] whereArgs) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
            case LEADERS:
                count = db.update(Provider.HuaWeiColumns.TABLE_NAME, values, where, whereArgs);
                break;

//            case LEADER_ID:
//                String noteId = uri.getPathSegments().get(1);
//                count = db.update(Provider.HuaWeiColumns.TABLE_NAME, values, Provider.HuaWeiColumns._ID + "=" + noteId
//                        + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
//                break;

            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        Objects.requireNonNull(getContext()).getContentResolver().notifyChange(uri, null);
        return count;
    }

    static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(Provider.HuaWeiColumns.AUTHORITY, "authentication", LEADERS);
//        sUriMatcher.addURI(Provider.HuaWeiColumns.AUTHORITY, "authentication/#", LEADER_ID);

        HashMap<String, String> sLeadersProjectionMap = new HashMap<String, String>();
//        sLeadersProjectionMap.put(Provider.HuaWeiColumns._ID, Provider.HuaWeiColumns._ID);
        sLeadersProjectionMap.put(Provider.HuaWeiColumns.NAME, Provider.HuaWeiColumns.NAME);
        sLeadersProjectionMap.put(Provider.HuaWeiColumns.VALUE, Provider.HuaWeiColumns.VALUE);
    }
}